package com.app.project;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

import com.app.DB.Segway;
import com.app.project.BESM_SplashActivity.Loading;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.view.Window;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class BESM_BluetoothConnect extends Activity {
	private BluetoothAdapter mBluetoothAdapter;
	static final ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();;
	private SimpleAdapter adapter;
	private ListView listview;
	ResultSet rs;
	public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
	private ProgressDialog mProgressDialog;
	private Boolean CheckLogin = false;
	private String BluetoothLogin;
	Intent intent;
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.activity_bluetooth);
		
		mBluetoothAdapter =BluetoothAdapter.getDefaultAdapter();
		if(mBluetoothAdapter == null){
			Toast.makeText(this, "Device dose not support Bluetooth", Toast.LENGTH_LONG).show();
		}
		if(!mBluetoothAdapter.isEnabled()){
			Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivityForResult(enableBtIntent, 1);
		}
		
		createSimpleAdapter();
		listview = (ListView) findViewById(R.id.Device_list);
		setProgressBarVisibility(true);
		if(mBluetoothAdapter.isDiscovering()){
			mBluetoothAdapter.cancelDiscovery();
		}
		mBluetoothAdapter.startDiscovery();
		ensureDiscoverable();
		Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
		setProgressBarIndeterminateVisibility(true);
		
		//find paired device
		if(pairedDevices.size() >0){
			
			for(BluetoothDevice device : pairedDevices){
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("Device Name", device.getName());
				map.put("Device Address", device.getAddress());
				list.add(map);
			}
		}
		
		//find Bluetooth device
		IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
		registerReceiver(mReceiver, filter);
		
		filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		this.registerReceiver(mReceiver, filter);
		
		//Start Activity when click on device item
		listview.setOnItemClickListener(new OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				
				// TODO Auto-generated method stub
				intent = new Intent(BESM_BluetoothConnect.this,BESM_LoginActivity.class);
				if(position >=0){
					intent.putExtra("Device Name", list.get(position).get("Device Name"));
					intent.putExtra("Device Address", list.get(position).get("Device Address"));
					
				}
				BluetoothLogin=list.get(position).get("Device Name");
				new  Loading().execute();
				//Toast.makeText(BESM_BluetoothActivity.this,String.valueOf(position)+" " + list.get(position).get("Device Name").toString(), Toast.LENGTH_LONG).show();
				
				
				//startActivityForResult(intent, RESULT_OK);
				//startActivity(intent);
				
			}
		});
		listview.setAdapter(adapter);
	}
	
	public void Alert_Car(final String DeviceName) {
        new AlertDialog.Builder(BESM_BluetoothConnect.this)
        .setTitle("Car Not Activate")
        .setMessage(DeviceName+" Not Activate, Please try to select car")
        .setIcon(R.drawable.notwifi)
                .setNegativeButton(android.R.string.yes, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface arg0, int arg1) {
//                    	CheckLogin(DeviceName);
                    }
                }).create().show();
	} 
	
	private void ensureDiscoverable(){
		if(mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE){
			Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
			discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
			startActivity(discoverableIntent);
		}
	}
	
	protected void onDestroy(){
		super.onDestroy();
		if(mBluetoothAdapter != null){
			mBluetoothAdapter.cancelDiscovery();
		}
		this.unregisterReceiver(mReceiver);
	}
	
	protected void  onActivityResult(int requestCode,int resultCode,Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		if(resultCode==1){
			if(resultCode==RESULT_OK){
				Toast.makeText(this, "Enabled Bluetooth succeed", Toast.LENGTH_LONG).show();
			}else if(resultCode==RESULT_CANCELED){
				Toast.makeText(this, "Can't Enabled Bluetooth", Toast.LENGTH_LONG).show();
			}
		}
		
	}
	
	private final BroadcastReceiver mReceiver =new BroadcastReceiver(){
		public void onReceive(Context context, Intent intent){
			String action = intent.getAction();
			if(BluetoothDevice.ACTION_FOUND.equals(action)){
				BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				if(device.getBondState() != BluetoothDevice.BOND_BONDED){
					HashMap<String, String> map = new HashMap<String, String>();
					map.put("Device Name", device.getName());
					map.put("Device Address", device.getAddress());
					list.add(map);
				}
				createSimpleAdapter();
				listview.setAdapter(adapter);
			}else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
				setProgressBarVisibility(false);
				if(adapter.getCount() == 0){
					//Toast.makeText(context, "No device found.", Toast.LENGTH_SHORT).show();
				}
			}
		}
	};
	
	public void createSimpleAdapter(){
		adapter = new SimpleAdapter(this, list, R.layout.activity_selectbluetooth, 
				new String[]{"Device Name","Device Address"}, 
				new int[]{R.id.DeviceName, R.id.DeviceAddress});
	}
	
	@Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DIALOG_DOWNLOAD_PROGRESS:
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage("Loading.....");
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            mProgressDialog.setCancelable(true);
            mProgressDialog.show();
            return mProgressDialog;
        default:
            return null;
        }
    }
	 // Download Image in Background
    public class Loading extends AsyncTask<String, Void, Void> {
        @SuppressWarnings("deprecation")
		protected void onPreExecute() {
        	super.onPreExecute();
        	showDialog(DIALOG_DOWNLOAD_PROGRESS);
        }
        @Override
        protected Void doInBackground(String... params) {
            // TODO Auto-generated method stub
        	//SystemClock.sleep(5000);
        	Segway usr = new Segway();
        	try{
        		rs = usr.selectSegway(BluetoothLogin);
        		if(rs.next()){
        			CheckLogin = true;
        		}
        	}catch (Exception e){
        	}
    		return null;
        }

        @SuppressWarnings("deprecation")
		protected void onPostExecute(Void unused) {
            dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
            removeDialog(DIALOG_DOWNLOAD_PROGRESS);
            if(CheckLogin){
				setResult(RESULT_OK,intent);
				list.clear();
//				mBluetoothAdapter.cancelDiscovery();
				finish();
			}else{
				Alert_Car(BluetoothLogin);
			}
        }
        
    }
	
}
